(function(){
  
/*定义参数常量*/
var ACTID  = '24';
var USERID = '';
var c = {
    ajax: {
        lotteryProductsqnj: '/inviteuser-lottery/invite-number',
        lotteryProducts: '/inviteuser-lottery/products',
        lotteryDraw: '/inviteuser-lottery/draw',
    }
};

// var mock = {
//     lotteryCount: 3,
//     products:[
//         {
//             id:1,
//             name: '限定座驾火焰战车30天',
//             imgUrl: '/christmas_draw/images/products/4.png',
//         },
//         {
//             id:2,
//             name: '限定座驾游艇15天',
//             imgUrl: '/christmas_draw/images/products/5.png',
//         },
//         {
//             id:3,
//             name: '限定座驾火焰战车15天',
//             imgUrl:'/christmas_draw/images/products/4.png',
//         },
//         {
//             id:4,
//             name: '贵族勋章国王30天',
//             imgUrl: '/christmas_draw/images/products/1.png',
//         },
//         {
//             id:5,
//             name: '限定座驾飞机15天',
//             imgUrl: '/christmas_draw/images/products/2.png',
//         },
//         {
//             id:6,
//             name: '贵族勋章骑士7天',
//             imgUrl: '/christmas_draw/images/products/3.png',
//         }
//     ]
// }

/**
 * 查找数组中子元素指数属性所在的index索引
 * @param  {[String]} key [要匹配的元素key值]
 * @param  {[String]} value [要匹配的元素key所对应的value]
 * @param  {[Array]} arr [{id:1,name:'11'},{id:2,name:'22'}]
 * @return console.log(findIndex('id', 2, [{id:1,name:'11'},{id:2, name:'22'}])) // 1;
 */
function findIndex(key, value, arr){
    console.log(arr)
    var idx = null;
    arr.some((item, index) => {
        if(item[key] === value){
            idx = index;
            return true;
        }
    });
    return idx;
}


function sortProducts(products, pid){
    var arr = products.concat(products);
    var res = [];
    var len = products.length;
    var min = -1;

    for(var i = 0; i < len*2; i++){
        if(arr[i].id == pid){
            min = i;
        }
        if(min > -1 && res.length < len){
            res.push(arr[i]);
        }
    }
    return res;
}

function setDis(){
    $('#lottery-handler').addClass('dis');
}

function initLottry(options){
    var width = $('#lottery').width();
    width = Math.round(width/10) * 10;

    $('#lottery').css({
        'width': width,
        'height': width,

    }).attr({
        width: width,
        height: width,
    });

    var _lottery = new Lottery(byId('lottery'), {
        handler: byId('lottery-handler'),
        handlerCallback: options.handlerCallback,
        products: options.products,
        outerRadius: Math.ceil(width/2*0.895),
        innerRadius: 0,
        fillStyle: ['#ffdf8a', '#fffdc9'],
        dpr: 1,
        //breakText: ['国王', '飞机', '骑士','火焰战车','游艇'],
        scale: XT.ua.isIos ? 1 : 2,
        font: {
            y: '-82%',
            color: XT.ua.isIos ? '#ff6527' : '#ff6527',
            style: 'normal',
            weight: 500,
            size: parseInt((width/632)*24),
            lineHeight: 1,
            family: '黑体'
        },
        images: {
            y: '-42%',
            width: (width/606)*179,
            height: (width/605)*91,
        },
        speed: XT.ua.isIos ? 18 : 18
    });
}


function byId(selector){
    return document.getElementById(selector);
}

/*
    获取到userId, 初始化页面
 */
function _initPage(cb){
    if(USERID > 0){
        cb && cb();
    }else{
        XT.bridge.call('getUserInfo', {}, function (res) {
            var info = JSON.parse(res);
            USERID = info.id;
            cb && cb(info);
        });
    }
}

_initPage(function(userInfo){

    var store = new Vuex.Store({
        state: {
            activity: {expired: false},
        },
        actions: {
            'get_lottery_products'({commit, state}, params){
                XT.jsonp({
                    url: XT.interface.fun(c.ajax.lotteryProducts),
                    data: params.data,
                    success: function(data){
                        data.products.length=6;
                        params.callback(data);
                    }
                });
            },
            
            'get_lotteryProductsqnj'({commit, state}, params){
                XT.jsonp({
                    url: XT.interface.fun(c.ajax.lotteryProductsqnj),
                    data: params.data,
                    success: function(data){
                        // data.lotteryCount = 1;
                        params.callback(data);
                    },
                    validMsg: function(msg){
                        params.callback(msg, true);
                    }
                });
            },
            'get_lottery_draw'({commit, state}, params){
                XT.post({
                    url: XT.interface.fun(c.ajax.lotteryDraw),
                    data: params.data,
                    success: function(data){
                        params.callback(data);
                    },
                    validMsg: function(msg){
                        params.callback(msg, true);
                    }
                });

                // params.callback({id:2, name:'xxx'})
            },
        },
        mutations: {
            'set_lottery_products'(state, data){
                state.lottery_products = data
            },
        }
    });


    $('body').on('click', '.dis', function(){
        App.modalClass = 'popup_over';
        App.popup_title='您已经抽过奖啦';
        App.lotteryName='祝您圣诞快乐呦~';
    });

    
    var App = new Vue({
        el: '#app',
        store: store,
        data: {
            /*dialog部分*/
            modalState: '',
            lotteryName: '',
            modalClass: 'zjwin',
            lotteryCount: 0,
            qnkdatalist:{
                 
            },
            popup_title:'恭喜！'

        },
        methods:{
            setModal: function(state){
                this.modalState = state;
            },
            closeModal: function(){
                this.modalState = '';
            },
            drawClick: function(){
                if(this.lotteryCount < 1){
                    this.setModal(2);
                    this.modalClass = 'popup_over';
                }
            },
            draw: function(fn){
                this.$store.dispatch('get_lottery_draw', {
                    data: {actId:ACTID,userId:USERID}, 
                    callback: fn
                });
            },
        },
        computed:{
            'activity'(){
                return this.$store.state.activity;
            },
        },
        mounted: function(){
            var self = this;
            self.$store.dispatch('get_lottery_products',  {
                data: {userId: USERID,actId:ACTID}, 
                callback: function(data){
                    $('body').removeClass('g-loading');
                    initLottry({
                        products: data.products,
                        handlerCallback: function(_interface){
                            self.lotteryCount--;
                            self.draw(function(res, isFail){
                                if(isFail){
                                    _interface.stop(0, function(){
                                        XT.message(res);
                                    });
                                }else{
                                    var stopIndex = findIndex('id', res.id, data.products);
                                    _interface.stop(stopIndex, function(){
                                        self.lotteryName = res.name;
                                        console.log(stopIndex);
                                        if(self.lotteryCount < 1){
                                            setDis();  
                                        }
                                    });
                                }

                            });
                        }
                    });
                }
            });
            self.$store.dispatch('get_lotteryProductsqnj', {
                data: {actId: ACTID, userId: USERID},
                callback: function(data){
                    if(data.lotteryCount < 1){
                        setDis();
                    }
                    self.lotteryCount = data.lotteryCount;
                }
            })
        },
        filters: {
            parseInt: function(value){
                return parseInt(value) || 0;
            },
        },
    });
    window.App = App;

});

// /*跑马灯效果*/
// function mqu(elem) {
//     var oElem = document.getElementById(elem);
//     if(!oElem)return;
//     var step = 2;
//     var timers = null;
//     var iH = oElem.offsetHeight/2;
//     var iTop = oElem.offsetTop || 0;

//     if (Math.abs(iTop - step) > iH) {
//         iTop = 0;
//     } else {
//         iTop -= step;
//     }
//     oElem.style.top = iTop + 'px';
//     clearTimeout(timers);
//     timers = setTimeout(function () {
//         mqu(elem);
//     }, 30);
// }

// mqu('j-winner-list');


}());




